package com.yidont.douyinhelper

import android.accessibilityservice.AccessibilityService
import android.content.Intent
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import com.yidont.douyinhelper.data.configData
import com.yidont.douyinhelper.data.followBean
import com.yidont.douyinhelper.ui.LogWindow
import com.yidont.douyinhelper.util.loge
import kotlinx.coroutines.*

class DouYinHelperService : AccessibilityService() {

    private val scope = MainScope()
    private lateinit var wm: WindowManager
    private lateinit var logWindow: LogWindow
    private lateinit var followHelper: FollowHelper

    override fun onServiceConnected() {
        super.onServiceConnected()
        loge("onServiceConnected")
        initLogWindow()
        followHelper = FollowHelper(this)
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        if (configData.showLogWindow.value != true){
            loge("已停止，请打开App重新运行")
            return
        }
        event ?: return
        loge(AccessibilityEvent.eventTypeToString(event.eventType))
        val active = rootInActiveWindow
        followHelper.run(logWindow, active)
    }

    private fun initLogWindow() {
        wm = getSystemService(WINDOW_SERVICE) as WindowManager
        logWindow = LogWindow(this)
        configData.showLogWindow.observeForever(observer)
    }

    private val observer = Observer<Boolean> {
        if (it) addLogWindow() else removeLogWindow()
    }

    private fun addLogWindow() {
        loge("addLogWindow")
        try {
            wm.addView(logWindow.view, logWindow.lp)
        } catch (e: Exception) {
            loge("addLogWindow error", e)
        }
    }

    private fun removeLogWindow() {
        loge("removeLogWindow")
        try {
            followHelper.stop()
            wm.removeView(logWindow.view)
        } catch (e: Exception) {
            loge("removeLogWindow error", e)
        }
    }

    override fun onInterrupt() {
        loge("onInterrupt")
    }

    override fun onUnbind(intent: Intent?): Boolean {
        loge("onUnbind")
        configData.showLogWindow.removeObserver(observer)
        followHelper.stop()

        scope.cancel()
        return super.onUnbind(intent)
    }

}